//
//  DetailViewController.m
//  TestReader
//
//  Created by 李雷川 on 2018/1/28.
//  Copyright © 2018年 李雷川. All rights reserved.
//

#import "CBCBookDetailViewController.h"
#import "RequestConfig.h"
#import "BookInfoRequest.h"
#import "ChapterRequest.h"
#import "DirectoryRequest.h"
#import <CBCReader/CBCReader.h>
#import "BookDetail.h"
#import "iTools.h"
@interface CBCBookDetailViewController ()<UIWebViewDelegate>
@property(nonatomic, strong)UIWebView *webView;
@property(nonatomic, strong)NSString *url;
@property(nonatomic, strong)CBCReadModel *readModel;
@property(nonatomic,strong)BookInfoRequest *bookInfoRequest;
@property(nonatomic,strong)ChapterRequest *chapterRequest;
@property(nonatomic,strong)DirectoryRequest *directoryRequest;
@property(nonatomic, strong)BookInfo *bookInfo;
@property(nonatomic, strong)NSArray<Chapter *> *chapters;
@end

@implementation CBCBookDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.webView];
    [self.view addSubview:[self readingButton]];
    //生成联网请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    
    //设置header
    [request addValue:[RequestConfig ContentType] forHTTPHeaderField:@"Content-Type"];
    [request addValue:[RequestConfig UserAgent] forHTTPHeaderField:@"User-Agent"];
    [request addValue:[RequestConfig getXClient] forHTTPHeaderField:@"X-Client"];
    
    request.cachePolicy = NSURLRequestReloadIgnoringCacheData;//忽略本地缓存
    [self.webView loadRequest:request];
    
    [self initData];
}

-(UIWebView *)webView{
    if(_webView == nil){
        _webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
        _webView.delegate = self;
    }
    return _webView;
}


-(UIButton *)readingButton{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(tapStartReading:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"开始阅读" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.backgroundColor = [UIColor colorWithRed:252/255.0 green:47/255.0 blue:0 alpha:1.0];
    button.frame = CGRectMake(0, self.view.frame.size.height - 44, self.view.frame.size.width, 44);
    return button;
}


//初始化数据
-(void)initData{
    [self requestBookInfo];
}
-(void)initChaptersWithJson:(NSString *)jsonContent{
    NSString * json = [NSString stringWithContentsOfFile:jsonContent encoding:NSUTF8StringEncoding error:nil];
    NSDictionary * dic = [self parseJSONStringToNSDictionary:json];
    
    NSArray *chapterList = [dic valueForKey:@"chapterList"];
    NSMutableArray *mutableChapters = [NSMutableArray array];
    [chapterList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *chapterDic = obj;
        Chapter *chapter = [Chapter chapterWithDictionary:chapterDic];
        [mutableChapters addObject:chapter];
    }];
    self.chapters = mutableChapters;
}
//请求图书详情
-(void)requestBookInfo{
    if(_bookInfoRequest == nil){
        _bookInfoRequest = [[BookInfoRequest alloc]init];
    }
    __weak CBCBookDetailViewController *weakSelf = self;
    [_bookInfoRequest startRequest:_bookID success:^(NSObject *o) {
        weakSelf.bookInfo = (BookInfo *)o;
        if([CBCReadTools isDonwloadedBookDirectoryJson:weakSelf.bookID] == NO || weakSelf.bookInfo.serial){
            [weakSelf downloadCatalogJson];
        }
        else{
            NSString *jsonPath = [CBCReadTools getBookChapterJsonPath:weakSelf.bookID];
            [weakSelf initChaptersWithJson:jsonPath];
            [weakSelf initReadModel];
        }
        
    } fail:^(NSObject *o) {
  
    }];
}

-(void)downloadCatalogJson{
    NSString *downloadUrl = [CBCReadTools getChapterJsonUrl:_bookID];
    NSString *jsonContent  = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:downloadUrl] encoding:NSUTF8StringEncoding error:nil];
    if(jsonContent == nil){
        [self requesDirectorys];
    }
    else{
        NSString *jsonPath = [CBCReadTools getBookChapterJsonPath:_bookID];
        BOOL success =  [jsonContent writeToFile:jsonPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        if(success){
            [self initChaptersWithJson:jsonPath];
            [self initReadModel];
        }
    }
    
    
}

-(void)requesDirectorys{
    if(_directoryRequest == nil){
        _directoryRequest = [[DirectoryRequest alloc]init];
    }
    __weak CBCBookDetailViewController *weakSelf = self;
    [_directoryRequest startRequest:_bookID success:^(NSObject *o) {
        BookDetail *bookDetail = (BookDetail *)o;
        weakSelf.chapters = bookDetail.chapters;
        [weakSelf initReadModel];
        
    } fail:^(NSObject *o) {
        if(o){
            NSString* message = (NSString*)o;
//            [iTools showCBCProgressHUDLabel:@"" detailLabelText:message];
        }else{
//            [iTools showCBCProgressHUDLabel:@"" detailLabelText:@"联网竟然失败了，还没有返回错误信息！😢"];
        }
    }];
}

-(void)initReadModel{
    self.readModel = [[CBCReadModel alloc]initWithBookInfo:_bookInfo andChapters:_chapters];
}

-(void)tapStartReading:(UIButton *)snder{
    if(self.readModel){
        CBCReadPageViewController *readViewController = [[CBCReadPageViewController alloc]initWithReadModel:self.readModel];
        readViewController.isHiddenShare = YES;
        [self.navigationController pushViewController:readViewController animated:YES];
    }

}
-(id)initWithUrl:(NSString *)url{
    if(self == [super init]){
        self.url = url;
    }
    return self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//字符串转字典
-(NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    if (JSONString) {
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        return responseJSON;
    }
    return @{};
    
}
@end
